package cn.swu.Waimai.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.swu.Waimai.R
import cn.swu.Waimai.center.LoginData
import cn.swu.Waimai.logic.dao.LoginHelper
import cn.swu.Waimai.ui.viewModel.UserViewModel
import kotlinx.android.synthetic.main.activity_login_password.*

//密码登录页面
class LoginActivity : BaseActivity() {
    private val viewModel by lazy { ViewModelProvider(this).get(UserViewModel::class.java) }

    @SuppressLint("CommitPrefEdits")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login_password)

        login_password_delete.setOnClickListener {
            onBackPressed()
        }

        agree_register.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }

        //点击登录
        agree_login.setOnClickListener {
            val phone = entered_phone.text.toString()
            val password = entered_password.text.toString()

            val dbHelper = LoginHelper(this, "USERLOGIN.db", 2)
            val db = dbHelper.writableDatabase
            val cursor = db.query("TODOLIST", null, null, null, null, null, null)

            if (cursor.moveToFirst()) {

                do {
                    val phones = cursor.getString(cursor.getColumnIndex("phone"))
                    val passwords = cursor.getString(cursor.getColumnIndex("password"))
                    if (phone == phones && password == passwords) {
                        LoginData.LOGIN_STATUS = 1
                        val editor = getSharedPreferences("login", Context.MODE_PRIVATE).edit()
                        editor.putString("phone", phone)
                        editor.putString("password", password)
                        editor.apply()
                        val intent = Intent(this, MenuActivity::class.java)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this, "登陆失败！", Toast.LENGTH_SHORT).show()
                    }
                } while (cursor.moveToNext())

            }

        }
    }
}
